import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/model/exam.dart';
import 'package:kxy_flutter_app/view/examination/do_exam_view.dart';
import 'package:kxy_flutter_app/view/examination/exam_status_widget.dart';

import 'time_line_item_widget.dart';

class TimelineExamWidget extends StatelessWidget {
  final List<Exam> examList;
  final Function refresh;
  const TimelineExamWidget({
    Key key,
    @required this.examList,
    @required this.refresh,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 20),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: createTimeLineList(context),
      ),
    );
  }

  Widget examWidget(Exam exam) {
    return Text(exam.name);
  }

  Widget monthWidget(DateTime date) {
    return Text(
      date.year == DateTime.now().year ? '${date.month}月' : '${date.year}年${date.month}月',
      style: TextStyle(
        fontSize: 18,
        fontWeight: FontWeight.bold,
      ),
    );
  }

  List<Exam> getExamListByMonth(DateTime date) {
    return examList.where((item) => item.startTime.year == date.year && item.startTime.month == date.month).toList();
  }

  List<Widget> createTimeLineList(BuildContext context) {
    List<DateTime> dateList = new List<DateTime>();
    examList.forEach((exam) {
      var date = new DateTime(exam.startTime.year, exam.startTime.month);
      if (!dateList.contains(date)) {
        dateList.add(date);
      }
    });

    List<Widget> timelineList = new List<Widget>();
    for (var i = 0; i < dateList.length; i++) {
      var date = dateList[i];
      timelineList.add(
        new TimeLineItem(
          child: monthWidget(date),
          isPrimary: true,
        ),
      );

      var examRange = getExamListByMonth(date);
      for (var n = 0; n < examRange.length; n++) {
        bool isLatest = i == dateList.length - 1 && n == examRange.length - 1;
        var timeLineItem = new TimeLineItem(
          isLatest: isLatest,
          child: examItemWidget(examList[n], context),
        );
        timelineList.add(timeLineItem);
      }
    }
    return timelineList;
  }

  Widget examItemWidget(Exam exam, BuildContext context) {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(5),
        boxShadow: [
          BoxShadow(
            color: Color.fromRGBO(240, 240, 240, 1),
            offset: Offset(1, 1),
          ),
          BoxShadow(
            color: Color.fromRGBO(240, 240, 240, 1),
            offset: Offset(-1, -1),
          ),
        ],
      ),
      child: ListTile(
        title: getExamTitle(exam),
        subtitle: getExamSubTitle(exam, context),
        trailing: Icon(
          Icons.chevron_right,
          size: 24,
          color: Colors.grey,
        ),
        onTap: () async {
          if (exam.status != ExamStatus.Started) {
            Fluttertoast.showToast(msg: '考试未开始或已结束');
            return;
          }
          var confirm = await confirmExam(context);
          if (confirm == null || !confirm) return;

          await Navigator.push(
            context,
            MaterialPageRoute(
              builder: (cxt) => DoExamView(exam: exam),
            ),
          );
          refresh();
        },
      ),
    );
  }

  Future<bool> confirmExam(BuildContext context) async {
    return showDialog(
      context: context,
      builder: (cxt) {
        return AlertDialog(title: Text('提示'), content: Text('您确认进入本场考试吗？'), actions: [
          FlatButton(
            child: Text('取消'),
            onPressed: () {
              Navigator.pop(context, false);
            },
          ),
          FlatButton(
            child: Text('确认'),
            onPressed: () {
              Navigator.pop(context, true);
            },
          ),
        ]);
      },
    );
  }

  Widget getExamTitle(Exam exam) {
    return Text(
      exam.name,
      style: TextStyle(
        fontSize: 16,
        color: Colors.black87,
      ),
    );
  }

  Widget getExamSubTitle(Exam exam, BuildContext context) {
    var statusText = exam.isJoin ? (exam.isPass ? '已及格' : '未及格') : '未答题';
    var statusColor = exam.isPass ? Theme.of(context).primaryColor : Colors.black54;
    return Padding(
      padding: EdgeInsets.only(top: 10),
      child: Row(
        children: [
          ExamStatusWidget(exam: exam),
          Text(
            statusText,
            style: TextStyle(
              color: statusColor,
              fontSize: 13,
            ),
          ),
          Text(
            '  |  ',
            style: TextStyle(
              fontSize: 10,
              color: Colors.black54,
            ),
          ),
          Text(
            '19题',
            style: TextStyle(
              fontSize: 13,
              color: Colors.black54,
            ),
          ),
        ],
      ),
    );
  }
}
